﻿<%@ WebHandler Language="C#" Class="PersonalCenter" %>

using System;
using System.Web;
using System.Text;
using System.Collections.Generic;
using Chenxin.Lib.Utility;
using System.Data;
using OpenFlashChart;

public class PersonalCenter : AjaxHandlerBase
{

    override public void RequestProcess(HttpContext context)
    {
        context.Response.Buffer = true;
        context.Response.ExpiresAbsolute = DateTime.Now.AddDays(-1);
        context.Response.AddHeader("pragma", "no-cache");
        context.Response.AddHeader("cache-control", "");
        context.Response.CacheControl = "no-cache";
        
        
        context.Response.ContentType = "application/json";

        if (context.Request["op"] != null)
        {
            switch (context.Request["op"].ToLower())
            {
                case "createnewpassword":
                    CreateNewPassword(context);
                    break;
                case "changepwd":
                    ChangePwd(context);
                    break;
                case "handlelogin":
                    break;
                case "getlist":     //得到主营楼盘
                    GetList(context);
                    break;
                case "add":     //添加主营楼盘
                    Add(context);
                    break;      
                case "del":     //删除主营楼盘
                    Del(context);
                    break;
                case "userpic":     //更换用户头像
                    ChangePic(context);
                    break;
                case "remarkwork":
                    RemarkWork(context);
                    break;
                case "dashbord":
                    DashBord(context);
                    //GlassBarDashBord(context);
                    break;
            }
        }
    }

    private DataTable GetData(HttpContext context)
    {

        StringBuilder strWhere = new StringBuilder(string.Format(" datediff(m,House_DataCollection.AddTime,'{0}')=0 and", DateTime.Now));


        //权限判断
        //全权限
        if (CurrentUserInfo.ContainsPermit(Constants.Permit_ViewAllArchivement))
        {
            strWhere.Append(" 1=1 ");
        }
        //城市权限
        else if (CurrentUserInfo.ContainsPermit(Constants.Permit_ViewCityArchivement))
        {
            strWhere.AppendFormat(" House_DataCollection.CityId='{0}'", CurrentUserInfo.CityId);
        }
        //公司权限
        else if (CurrentUserInfo.ContainsPermit(Constants.Permit_ViewCompanyArchivement))
        {
            strWhere.AppendFormat(" House_DataCollection.CompanyId='{0}'", CurrentUserInfo.CompanyId);
        }
        //部门权限
        else if (CurrentUserInfo.ContainsPermit(Constants.Permit_ViewDepartArchivement))
        {
            //strWhere.AppendFormat(" House_DataCollection.DepartId='{0}'", CurrentUserInfo.DepartId);
            strWhere.Append(" EXISTS(");
            strWhere.Append("Select 1 from V_Struct_UserDepartRelation M ");
            strWhere.Append("WHERE House_DataCollection.DepartId=M.DepartId ");
            strWhere.Append("And ViewBusiness=1 ");
            strWhere.Append("And IsOpen = 1 ");
            strWhere.Append("And IsCalculate = 1 ");
            strWhere.Append("And DepartKind <> '总部' ");
            strWhere.AppendFormat("And M.Userid= '{0}' ", CurrentUserInfo.UserId);
            strWhere.Append(") ");
        }
        //个人权限
        else
        {
            strWhere.AppendFormat(" House_DataCollection.UserId='{0}'", CurrentUserInfo.UserId);
        }


        DataSet ds = Chenxin.Lib.House.DAL.House_DataCollection.GetArchivementCount(strWhere.ToString());
        if (ds.Tables.Count > 0)
        {
            return ds.Tables[0];
        }
        return new DataTable();
    }

    /// <summary>
    /// FlashChart
    /// </summary>
    /// <param name="context"></param>
    private void DashBord(HttpContext context)
    {
        OpenFlashChart.OpenFlashChart chart = new OpenFlashChart.OpenFlashChart();
        chart.Title = new Title("营业活动");

        List<BarGlassValue> values = new List<BarGlassValue>();
        List<string> labels = new List<string>();


        BarGlass bar = new BarGlass();
        bar.Set_Key("营业活动", 12);
        bar.Colour = "#0072E3";
        bar.FillAlpha = 0.8;
        
        DataTable dt = GetData(context);

        int max=1;


        string[] array=new string[5]{"房源","房源跟单","客需","客需跟单","带看"};


        
        if (dt.Rows.Count>0)
        {
            try
            {

                for (int i = 0; i < 5; i++)
                {
                    BarGlassValue _v = new BarGlassValue(double.Parse(dt.Rows[0].ItemArray[i].ToString()));
                    _v.Tip = array[i] + "：#val#条";

                    labels.Add(array[i]);
                    values.Add(_v);
                    if (max < Convert.ToInt32(dt.Rows[0].ItemArray[i]))
                    {
                        max = Convert.ToInt32(dt.Rows[0].ItemArray[i]);
                    }
                }
            }
            catch
            {
                for (int i = 0; i < 5; i++)
                {
                    BarGlassValue _v = new BarGlassValue(0);
                    _v.Tip = array[i] + "：#val#条";

                    labels.Add(array[i]);
                    values.Add(_v);
                }
            }
        }
        else
        {
            for (int i = 0; i < 5; i++)
            {
                labels.Add(array[i]);
                values.Add(new BarGlassValue(double.Parse("0")));           
            }
        }
        bar.Values = values;
        
        XAxis xaxis = new XAxis();
        xaxis.Labels.SetLabels(labels);
        xaxis.Offset = true;
        xaxis.Labels.FontSize = 12;
        chart.X_Axis = xaxis;

        YAxis yaxis = new YAxis();

        int step = 1;
        if (max > 10)
        {
            step = (int)(max / 10);
        }
        else
        {
            yaxis.Steps = 1;
        }
        yaxis.SetRange(0, max);
        yaxis.Steps = step;

        chart.Y_Axis = yaxis;
        chart.Y_Axis.SetRange(0, max, step);
        bar.Tooltip = "#bottom#：#val#";

        chart.AddElement(bar);


        string s = chart.ToPrettyString();
        context.Response.Write(s);
    }

    private void RemarkWork(HttpContext context)
    {
        string strType = context.Request["worktype"];
        try
        {
            
            //考勤记录实体
            Chenxin.Lib.Hr.Entity.Hr_AttendanceRecord entAttendanceRec = new Chenxin.Lib.Hr.Entity.Hr_AttendanceRecord();
            //考勤业务类
            Chenxin.Lib.Hr.BLL.Hr_AttendanceRecord bllAttendanceRec = new Chenxin.Lib.Hr.BLL.Hr_AttendanceRecord();
            //考勤周期业务类
            Chenxin.Lib.Hr.BLL.Struct_AttendanceCircle bllAttendanceCir = new Chenxin.Lib.Hr.BLL.Struct_AttendanceCircle();


            //现在时间
            DateTime dtNow = DateTime.Now;
            //考勤记录实体
            DataSet dsAttendanceRec = bllAttendanceRec.GetListByToday(CurrentUserInfo.UserId, dtNow);

            DataRow[] dtRec;

            if (strType == "Start")
            {
                dtRec = dsAttendanceRec.Tables[0].Select("Type='S'");
                if (dtRec.Length > 0)
                {
                    context.Response.Write(retExecResult(Constants.ExecResult.Error, "你已经登录过上班时间", ""));
                    return;
                }
            }
            else
            {
                dtRec = dsAttendanceRec.Tables[0].Select("Type='E'");
                if (dtRec.Length > 0)
                {
                    context.Response.Write(retExecResult(Constants.ExecResult.Error, "你已经登录过下班时间", ""));
                    return;
                }
            }
            
            //考勤周期实体类
            Chenxin.Lib.Hr.Entity.Struct_AttendanceCircle entAttendanceCir = bllAttendanceCir.GetModel();

            entAttendanceRec.RecordId = Guid.NewGuid();
            entAttendanceRec.DepartId = CurrentUserInfo.DepartId;
            entAttendanceRec.UserId = CurrentUserInfo.UserId;
            entAttendanceRec.UserCode = CurrentUserInfo.UserCode;
            
            //开始月和结束月份相同
            if (entAttendanceCir.StartMonthFlg == entAttendanceCir.EndMonthFlg)
            {
                entAttendanceRec.Year = dtNow.Year.ToString();
                entAttendanceRec.Month = dtNow.Month.ToString().PadLeft(2, '0');
            }
            else
            {
                //判断当前月份
                if (DateTime.Now.Day < entAttendanceCir.StartDate.Value)
                {
                    entAttendanceRec.Year = dtNow.Year.ToString();
                    entAttendanceRec.Month = dtNow.Month.ToString().PadLeft(2, '0');
                }
                else
                {
                    if (dtNow.Month == 12)
                    {
                        entAttendanceRec.Year = (dtNow.Year + 1).ToString();
                        entAttendanceRec.Month = "01";
                    }
                    else
                    {
                        entAttendanceRec.Year = dtNow.Year.ToString();
                        entAttendanceRec.Month = (dtNow.Month + 1).ToString().PadLeft(2, '0');
                    }
                }
            }

            entAttendanceRec.DateTime = DateTime.Now;
            entAttendanceRec.Time = DateTime.Now.ToLongTimeString();

            //上班
            if (strType == "Start")
            {
                entAttendanceRec.Type = "S";
            }
            //下班
            else
            {
                entAttendanceRec.Type = "E";
            }

            //添加记录
            bllAttendanceRec.Add(entAttendanceRec);

            context.Response.Write("{success:1,msg:'登记" + (strType == "Start" ? "上班" : "下班") + "成功！登记时间：" + DateTime.Now.ToString() + "',data:''}");
        }
        catch (Exception ex)
        {
            context.Response.Write("{success:1,msg:'登记" + (strType == "Start" ? "上班" : "下班") + "失败！登记时间：" + DateTime.Now.ToString() + "',data:''}");
        }
    }

    
    //更换用户头像
    private void ChangePic(HttpContext context)
    {
        try
        {
            string picurl = context.Request.Params["picurl"];
            string strSql = string.Format("update Hr_UserInfo set PicUrl='{0}',UpdateTime=getdate() where UserId='{1}'", picurl, CurrentUserInfo.UserId.ToString());
            Chenxin.Lib.Passport.DAL.Hr_UserInfo.ExecuteSQL(strSql);
            context.Response.Write(string.Format("{{success:'1',msg:'头像更新成功',data:''}}"));
        }
        catch (Exception ex)
        {
            context.Response.Write(string.Format("{{success:'0',msg:'{0}',data:''}}", ex.Message));
        }
    }
    


    //添加主营楼盘
    private void Add(HttpContext context)
    {
        try
        {
            Chenxin.Lib.House.Entity.House_EmployeeCommunitySetting model = (Chenxin.Lib.House.Entity.House_EmployeeCommunitySetting)JsonHelp.Convert2Entity(context.Request["model"], typeof(Chenxin.Lib.House.Entity.House_EmployeeCommunitySetting));
            model.RecordId = Guid.NewGuid();
            model.UserId = CurrentUserInfo.UserId;
            if (Chenxin.Lib.House.DAL.House_EmployeeCommunitySetting.checkcount(CurrentUserInfo.UserId.ToString()) < 5)
            {
                Chenxin.Lib.House.DAL.House_EmployeeCommunitySetting.Add(model);
                context.Response.Write(string.Format("{{success:'1',msg:'添加成功',data:''}}"));
            }
            else
                context.Response.Write(string.Format("{{success:'0',msg:'添加失败，最多添加5项主营楼盘！你已达上限！',data:''}}"));
        }
        catch (Exception ex)
        {
            context.Response.Write(string.Format("{{success:'0',msg:'{0}',data:''}}", ex.Message));
        }
    }
    
    
    //删除楼盘
    private void Del(HttpContext context)
    {
        try
        {
            string modelid = context.Request.Params["modelid"];
            Chenxin.Lib.House.DAL.House_EmployeeCommunitySetting.Delete(new Guid(modelid));
            context.Response.Write(string.Format("{{success:'1',msg:'删除成功',data:''}}"));
        }
        catch (Exception ex)
        {
            context.Response.Write(string.Format("{{success:'0',msg:'{0}',data:''}}", ex.Message));
        }
    }

    //得到主营楼盘的数据
    private void GetList(HttpContext context)
    {
        string strSql = string.Format("UserId='{0}'", CurrentUserInfo.UserId.ToString());
        DataSet ds = Chenxin.Lib.House.DAL.House_EmployeeCommunitySetting.GetList(strSql);
        int count = (int)ds.Tables[1].Rows[0][0];
        string strHtml = "";
        if (!GetKeyListHtml(ds, out strHtml))
        {
            context.Response.Write(string.Format("{{success:'0',msg:'{0}',data:''}}", "生成HTML错误:" + strHtml));
        }
        ds.Dispose();
        ds = null;
        context.Response.Write(string.Format("{{success:'1',msg:'{0}',data:{{count:'{1}',data:'{2}'}}}}", "成功", count, strHtml));
    }

    //生成部门列表的HTML
    private bool GetKeyListHtml(DataSet dslist, out string strHtml)
    {
        try
        {
            StringBuilder sb = new StringBuilder();
            sb.Append("<table width=\"100%\" height=\"100%\" cellspacing=\"1\" class=\"tabsorternew\" id=\"report\">");
            sb.Append("<thead><tr>");
            sb.Append("<th width=\"33%\">楼盘名称</th>");
            sb.Append("<th width=\"33%\">区域</th>");
            sb.Append("<th width=\"33%\" >板块</th>");
            sb.Append("</tr></thead><tbody>");

            foreach (DataRow row in dslist.Tables[0].Rows)
            {
                sb.AppendFormat("<tr id=\"{0}\" class=\"tr_houselist\" >", row["RecordId"].ToString());
                sb.AppendFormat("<td>{0}</td>", Chenxin.Lib.Utility.DatasetHelper.GetValue(row, "CommunityName", ""));
                sb.AppendFormat("<td>{0}</td>", Chenxin.Lib.Utility.DatasetHelper.GetValue(row, "Region", ""));
                sb.AppendFormat("<td>{0}</td>", Chenxin.Lib.Utility.DatasetHelper.GetValue(row, "Block", ""));
                sb.Append("</tr>");
            }

            sb.Append("</tbody></table>");
            strHtml = sb.ToString();
            return true;
        }
        catch (Exception ex)
        {
            strHtml = ex.Message;
            return false;
        }
    }

    /// <summary>
    /// 
    /// </summary>
    /// <param name="context"></param>
    public void HandleLogin(HttpContext context)
    {
        try
        {

            if (context.Request["userid"] != null)
            {
                //声称requestkey 并放入缓存，过期时间设置为60分钟
                string strRequestKey = Guid.NewGuid().ToString().Replace("-", "");
                string strCachedKey = string.Format(Chenxin.Lib.Cache.CacheDataType.GLOBAL_REQUEST, strRequestKey);
                Chenxin.Lib.Cache.CacheService cs = new Chenxin.Lib.Cache.CacheService(Chenxin.Lib.Cache.CacheConn.xCacheConn.GLOBAL);

                cs.Set(strCachedKey, context.Request["userid"], DateTime.Now.AddMinutes(60));

                //用户登录
                //用户Id保存到Cookie中
                HttpCookie ckRequestKey = new HttpCookie("requestkey", strRequestKey);
                context.Response.AppendCookie(ckRequestKey);
                context.Response.Write("{success:1,msg:'',data:''}");
            }
            else
            {
                context.Response.Write("{success:0,msg:'登录信息设置失败，请重新登录！',data:''}");                   
            }
        }
        catch
        {
            context.Response.Write("{success:0,msg:'登录信息设置失败，请重新登录！',data:''}");            
        }
    }
    
    /// <summary>
    /// 修改密码
    /// </summary>
    /// <param name="context"></param>
    public void ChangePwd(HttpContext context)
    {
        try
        {
            Chenxin.Lib.Passport.Entity.Hr_UserInfo model = Chenxin.Lib.Passport.DAL.Hr_UserInfo.GetEntityById(CurrentUserInfo.UserId);
            string oldPwd = System.Web.Security.FormsAuthentication.HashPasswordForStoringInConfigFile(context.Request["oldpwd"], "MD5");
            if (oldPwd == model.Password)
            {
                model.Password = System.Web.Security.FormsAuthentication.HashPasswordForStoringInConfigFile(context.Request["newpwd"], "MD5");
                model.PassUpdateTime = DateTime.Now;
                model.NeedChgPass = false;


                Chenxin.Lib.Passport.DAL.Hr_UserInfo.ChangePassword(model);
                context.Response.Write("{success:1,msg:'密码修改成功！',data:''}");
            }
            else
            {
                context.Response.Write("{success:0,msg:'原密码错误！',data:''}");
            }
        }
        catch
        {
            context.Response.Write("{success:0,msg:'密码修改失败！',data:''}");
        }
    }

    /// <summary>
    /// 生成新密码
    /// </summary>
    /// <param name="context"></param>
    public void CreateNewPassword(HttpContext context)
    {
        string newPwd = GenerateRandom(6);
        context.Response.Write("{success:1,msg:'',data:{newpwd:'" + newPwd.ToLower() + "'}}");
        
    }
  
    /// <summary>
    /// 生成随机数
    /// </summary>
    /// <param name="Length"></param>
    /// <returns></returns>
　　public static string GenerateRandom(int Length)
　　{
      char[] constant ={
　　　　　　　　　　　　　　'1','2','3','4','5','6','7','8','9',
　　　　　　　　　　　　　　'A','B','C','D','E','F','G','H','I','J',
　　　　　　　　　　　　　　'K','L','M','N','O','P','Q','R','S','T',
　　　　　　　　　　　　　　'U','V','W','X','Y','Z'
　　　　　　　　　　　　};
　　　　System.Text.StringBuilder newRandom = new System.Text.StringBuilder(35);
　　　　Random rd = new Random();
　　　　for (int i = 0; i < Length; i++)
　　　　{
　　　　　　newRandom.Append(constant[rd.Next(35)]);
　　　　}
　　　　return newRandom.ToString();
　　}
}